﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Saxxon.LibDoomSharp
{
    /// <summary>
    /// A wrapper for IO.BinaryReader that contains support for fixed length string fields and code page 437.
    /// </summary>
    public class DataReader : BinaryReader
    {
        /// <summary>
        /// Most common DOS code page (and incidentally the one used by Doom)
        /// </summary>
        const int DOS_CODEPAGE = 437;

        /// <summary>
        /// Instantiate a DataReader for the specified stream.
        /// </summary>
        public DataReader(Stream stream)
            : base(stream, Encoding.GetEncoding(DOS_CODEPAGE))
        {
        }

        /// <summary>
        /// Read a string from the stream in a fixed length field.
        /// </summary>
        public string ReadString(int bytes)
        {
            return TrimString(new string(ReadChars(bytes)));
        }

        /// <summary>
        /// Trim null and whitespace characters from a string.
        /// </summary>
        static protected string TrimString(string s)
        {
            string result = s;

            // terminate at null character
            if (result.Contains('\0'))
            {
                result = result.Substring(0, result.IndexOf('\0'));
            }

            // remove whitespace
            result = result.Trim();

            return result;
        }

    }
}
